package com.gearbox.platform.deadline.service;

import com.gearbox.core.model.shell.ShellResult;
import com.gearbox.core.util.CmdExecuteResultAssertion;
import com.gearbox.core.util.ShellExecutor;

import java.util.List;
import java.util.Locale;

public class DeadlineCommandExecutor {
    public static List<String> getSlaveNames() {
        ShellResult result = ShellExecutor.runCommand(String.format(Locale.ROOT, "deadlinecommand -GetSlaveNames"));
        CmdExecuteResultAssertion.assertError(result);
        return result.getReturnValues();
    }

    public static String getSlaveStatusByName(String slaveName) {
        ShellResult result = ShellExecutor.runCommand(
            String.format(Locale.ROOT, "deadlinecommand -GetSlaveInfo %s slavestatus", slaveName));
        CmdExecuteResultAssertion.assertError(result);
        return result.getReturnValues().get(0);
    }

    public static boolean isSlaveEnabled(String slaveName) {
        ShellResult result = ShellExecutor.runCommand(
            String.format(Locale.ROOT, "deadlinecommand -GetSlaveSetting %s SlaveEnabled", slaveName));
        CmdExecuteResultAssertion.assertError(result);
        return Boolean.parseBoolean(result.getReturnValues().get(0));
    }

    public static void deleteSlave(String slaveName) {
        String cmd = String.format(Locale.ROOT, "deadlinecommand -DeleteSlave %s", slaveName);
        ShellResult result = ShellExecutor.runCommand(cmd);
        CmdExecuteResultAssertion.assertError(result);
    }

    public static void disableSlave(String slaveName) {
        String cmd = String.format(Locale.ROOT, "deadlinecommand -setslavesetting %s slaveenabled false", slaveName);
        ShellResult result = ShellExecutor.runCommand(cmd);
        CmdExecuteResultAssertion.assertError(result);
    }

    public static List<String> listWaitingJobIds() {
        String getWaitingJobCmd = "deadlinecommand -GetJobIdsFilter status=queued status=rendering";
        ShellResult result = ShellExecutor.runCommand(getWaitingJobCmd);
        CmdExecuteResultAssertion.assertError(result);
        return result.getReturnValues();
    }

    public static String getJobUserName(String jobId) {
        String cmd = String.format(Locale.ROOT, "deadlinecommand -GetJobSetting %s UserName", jobId);
        ShellResult result = ShellExecutor.runCommand(cmd);
        CmdExecuteResultAssertion.assertError(result);
        return result.getReturnValues().get(0);
    }

    public static int getJobQueuedChunks(String jobId) {
        String cmd = String.format(Locale.ROOT, "deadlinecommand -GetJobSetting %s QueuedChunks", jobId);
        ShellResult result = ShellExecutor.runCommand(cmd);
        CmdExecuteResultAssertion.assertError(result);
        return Integer.parseInt(result.getReturnValues().get(0));
    }
}
